package da.asclass.socket
{
    import da.asclass.events.msg.MessageReceivedEvent;
    import da.asclass.events.net.SocketConnectEvent;

    import flash.events.Event;
    import flash.events.EventDispatcher;
    import flash.events.IEventDispatcher;
    import flash.events.IOErrorEvent;
    import flash.events.ProgressEvent;
    import flash.events.SecurityErrorEvent;
    import flash.net.SharedObject;
    import flash.net.Socket;

    import mx.controls.Alert;

    public class SocketConnect implements IEventDispatcher
    {
        private var socket:Socket = null;

        private var myShare:SharedObject = null;
        private var myDisp:EventDispatcher = null;

        public static const CONNECTED_EVENT:String = "CONNECTED_EVENT";
        public static const IO_ERROR_EVENT:String = "IO_ERROR_EVENT";
        public static const CLOSE_EVENT:String = "CLOSE_EVENT";

        public function SocketConnect ()
        {
            myDisp = new EventDispatcher();
        }

        public function initSocket ():void
        {
            this.socket = new Socket();
            this.socket.addEventListener( Event.CONNECT , connectHandler );
            this.socket.addEventListener( IOErrorEvent.IO_ERROR , errorHandler );
            this.socket.addEventListener( Event.CLOSE , closeHandler );
            this.socket.addEventListener( ProgressEvent.SOCKET_DATA , socketDataHandler );
            this.socket.addEventListener( SecurityErrorEvent.SECURITY_ERROR , securityEventHandler );
            this.socket.connect( "localhost" , 8888 );
        }

        /*
         * Send message to server
         */
        public function sendMessage ( message:String ):void
        {

            try
            {
                Alert.show( "in sendMessage" );
                this.socket.writeUTF( message + "\n" );
                this.socket.flush();
            }
            catch ( e:Error )
            {
                Alert.show( e.message );
            }
        }

        /*
         * Reveive message from the server and then dispatch the MessageRe
         */
        private function socketDataHandler ( event:ProgressEvent ):void
        {

            var message:String = null;
            if ( this.socket.bytesAvailable )
            {
                message = this.socket.readUTF();
                Alert.show( "socketDataHandler" + message );
            }
            new EventDispatcher().dispatchEvent( new MessageReceivedEvent( message ));
        }

        public function addEventListener ( type:String , listener:Function ,
            useCapture:Boolean = true , priority:int = 0 , useWeakReference:Boolean = false ):void
        {
            myDisp.addEventListener( type , listener , useCapture , priority , useWeakReference );
        }

        public function dispatchEvent ( event:Event ):Boolean
        {
            return myDisp.dispatchEvent( event );
        }

        public function hasEventListener ( type:String ):Boolean
        {
            return myDisp.hasEventListener( type );
        }

        public function removeEventListener ( type:String , listener:Function , useCapture:Boolean = false ):void
        {
            myDisp.removeEventListener( type , listener , useCapture );
        }

        public function willTrigger ( type:String ):Boolean
        {
            return myDisp.willTrigger( type );
        }

        /*
         * After the socket connected to the server,client send a register message to register socket to
         * userHash
         */

        private function connectHandler ( event:Event ):void
        {
            Alert.show( "socket is connected..." );
            new EventDispatcher().dispatchEvent( new SocketConnectEvent( SocketConnect.CONNECTED_EVENT ));
        }

        private function errorHandler ( event:IOErrorEvent ):void
        {
            Alert.show( "errHandler" );
            new EventDispatcher().dispatchEvent( new SocketConnectEvent( SocketConnect.IO_ERROR_EVENT ));
        }

        private function closeHandler ( event:Event ):void
        {
            Alert.show( "closeHandler" );
            new EventDispatcher().dispatchEvent( new SocketConnectEvent( SocketConnect.CLOSE_EVENT ));
        }

        private function securityEventHandler ( event:SecurityErrorEvent ):void
        {
            Alert.show( "securityHandler" );
            //   Alert.show( "in securityEventHandler" + event.type );
        }

        public function getString ():String
        {
            return "in toString SocketConnect";
        }
    }
}